Android  ImageView 원 각 효과 그리 기

12413 단어 ImageView원 각
머리말
안 드 로 이 드 개발 에서 우 리 는 항상 그림 의 원형/원 각 효 과 를 실현 해 야 한다.우 리 는 두 가지 방식 으로 이런 효 과 를 실현 할 수 있다.하 나 는 Xfermode 를 사용 하고 다른 하 나 는 BitmapShader 를 사용 하여 이 루어 집 니 다.다음은 이 두 가지 용법 을 각각 소개 하 겠 습 니 다.
Xfermode 방식 으로 구현
이 방식 의 핵심 코드 를 사용 하면 다음 과 같 습 니 다.

  private Bitmap creataBitmap(Bitmap bitmap) {

    //      Bitmap       
    Bitmap target = Bitmap.createBitmap(1000,1000, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(target);
    final Paint paint = new Paint();
    paint.setColor(Color.GREEN);
    paint.setAntiAlias(true);
    //               
    canvas.drawCircle(500,500,500,paint);
    //  Xfermode,  SRC_IN  ,                 
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    //              bitmap
    canvas.drawBitmap(bitmap,0,0,paint);
    return target;
  }

위 코드 에 서 는 지 정 된 캔버스 에 두 겹 의 그림 이 그 려 져 있 음 을 알 수 있 습 니 다.하 나 는 반경 500 픽 셀 의 원형 이 고,하 나 는 대상 비트 맵 을 위 에 그 리 는 것 입 니 다.paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)도 호출 되 었 습 니 다.IN));역할 은 이 두 개의 효과 도 를 중첩 한 후 두 번 째 그림 의 교 집합 도 를 얻 는 것 이다.그래서 우 리 는 먼저 원형 을 그린 다음 에 Bitmap 를 그리고 원형 으로 교차 하 며 꺼 낸 것 이 바로 원형 구역 의 Bitmap 입 니 다.
Porter Duff.Mode 에는 모두 16 가지 효과 가 있 습 니 다.다음 과 같 습 니 다.

모드 에 따라 표시 되 는 효과 도 를 제어 할 수 있 습 니 다.
적용 시작
1.사용자 정의 속성 은 attrs.xml 에 있 습 니 다.

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <attr name="borderRadius" format="dimension" />
  <attr name="type">
    <enum name="circle" value="0"/>
    <enum name="round" value="1"/>
  </attr>
  <attr name="src" format="reference"/>
  <declare-styleable name="RoundImageView">
    <attr name="borderRadius"/>
    <attr name="type"/>
    <attr name="src"/>
  </declare-styleable>

</resources>

2.사용자 정의 뷰

public class RoundImageView extends View {

  private int type;
  private static final int TYPE_CIRCLE = 0;
  private static final int TYPE_ROUND = 1;
  //  
  private Bitmap mSrc;
  //    
  private int mRadius;
  //  
  private int mWidth;
  //  
  private int mHeight;

  public RoundImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    //        
    TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.RoundImageView);
    //          
    int count = a.getIndexCount();
    for (int i=0 ; i<count ; i++){
      int attr = a.getIndex(i);
      switch (attr){
        case R.styleable.RoundImageView_borderRadius:
          int defValue = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10f,getResources().getDisplayMetrics());
          mRadius = a.getDimensionPixelSize(attr, defValue);
          break;
        case R.styleable.RoundImageView_type:
          type = a.getInt(attr,0);
          break;
        case R.styleable.RoundImageView_src:
          mSrc = BitmapFactory.decodeResource(getResources(),a.getResourceId(attr,0));
          break;
      }
    }

    a.recycle();
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    //    
    int specMode = MeasureSpec.getMode(widthMeasureSpec);
    int specSize = MeasureSpec.getSize(widthMeasureSpec);
    if (specMode == MeasureSpec.EXACTLY){
      mWidth = specSize;
    }else {
      int desireByImg = getPaddingLeft() + getPaddingRight() + mSrc.getWidth();
      if (specMode == MeasureSpec.AT_MOST)// wrap_content
      {
        mWidth = Math.min(desireByImg, specSize);
      } else
        mWidth = desireByImg;
    }

    //    
    specMode = MeasureSpec.getMode(heightMeasureSpec);
    specSize = MeasureSpec.getSize(heightMeasureSpec);
    if (specMode == MeasureSpec.EXACTLY){
      mHeight = specSize;
    }else {
      int desire = getPaddingTop() + getPaddingBottom() + mSrc.getHeight();
      if (specMode == MeasureSpec.AT_MOST)// wrap_content
      {
        mHeight = Math.min(desire, specSize);
      } else
        mHeight = desire;
    }

    setMeasuredDimension(mWidth,mHeight);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    switch (type){
      case TYPE_CIRCLE:
        int min = Math.min(mWidth,mHeight);
        //      Bitmap,            Bitmap。
        mSrc = Bitmap.createScaledBitmap(mSrc, min, min, false);
        canvas.drawBitmap(createCircleImage(mSrc, min), 0, 0, null);

        break;
      case TYPE_ROUND:
        mSrc = Bitmap.createScaledBitmap(mSrc, mWidth, mHeight, false);
        canvas.drawBitmap(createRoundConerImage(mSrc), 0, 0, null);

        break;
    }
  }

  /**
   *     
   * @param source
   * @return
   */
  private Bitmap createRoundConerImage(Bitmap source) {
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    Bitmap target = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(target);
    RectF rect = new RectF(0, 0, mWidth, mHeight);
    canvas.drawRoundRect(rect, mRadius, mRadius, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(source, 0, 0, paint);
    return target;
  }

  /**
   *     
   * @param source
   * @param min
   * @return
   */
  private Bitmap createCircleImage(Bitmap source, int min) {
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    Bitmap target = Bitmap.createBitmap(min, min, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(target);
    canvas.drawCircle(min/2,min/2,min/2,paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(source, 0, 0, paint);
    return target;
  }
}

3.레이아웃 파일

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:roundview="http://schemas.android.com/apk/res-auto"
       xmlns:tools="http://schemas.android.com/tools"
       android:id="@+id/activity_main"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical"
       android:padding="10dp"
       tools:context="mo.yumf.com.myviews.MainActivity">


  <mo.yumf.com.myviews.RoundImageView
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_marginTop="20dp"
    roundview:borderRadius="10dp"
    roundview:src="@drawable/ac_default_icon"
    roundview:type="round"/>

  <mo.yumf.com.myviews.RoundImageView
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_marginTop="20dp"
    roundview:src="@drawable/ac_default_icon"
    roundview:type="circle"/>
</LinearLayout>

위의 사용자 정의 View 에는 레이아웃 에 불 러 올 그림 자원 만 설정 할 수 있 고 코드 에 그림 을 설정 할 수 없 는 한계 가 있 습 니 다.다음 과 같은 방식 으로 사용자 정의 ImageView 를 선택 합 니 다.

public class RoundImageView extends ImageView {

  private int type;
  private static final int TYPE_CIRCLE = 0;
  private static final int TYPE_ROUND = 1;
  //  
  private Bitmap mSrc;
  //    
  private int mRadius;

  public RoundImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    //        
    TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.RoundImageView);
    //          
    int count = a.getIndexCount();
    for (int i=0 ; i<count ; i++){
      int attr = a.getIndex(i);
      switch (attr){
        case R.styleable.RoundImageView_borderRadius:
          int defValue = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10f,getResources().getDisplayMetrics());
          mRadius = a.getDimensionPixelSize(attr, defValue);
          break;
        case R.styleable.RoundImageView_type:
          type = a.getInt(attr,0);
          break;
      }
    }

    a.recycle();
  }

  @Override
  protected void onDraw(Canvas canvas) {
    if (getDrawable() != null){
      Bitmap bitmap = getBitmap(getDrawable());
      if (bitmap != null){
        switch (type){
          case TYPE_CIRCLE:
            //  ImageView    ,    
            int min = Math.min(getMeasuredWidth(),getMeasuredHeight());
            //      Bitmap,            Bitmap。
            mSrc = Bitmap.createScaledBitmap(bitmap, min, min, false);
            canvas.drawBitmap(createCircleImage(mSrc, min), 0, 0, null);

            break;
          case TYPE_ROUND:
            mSrc = Bitmap.createScaledBitmap(bitmap, getMeasuredWidth(), getMeasuredHeight(), false);
            canvas.drawBitmap(createRoundConerImage(mSrc), 0, 0, null);

            break;
        }
      }
    }else {

      super.onDraw(canvas);
    }
  }

  private Bitmap getBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable){
      return ((BitmapDrawable)drawable).getBitmap();
    }else if (drawable instanceof ColorDrawable){
      Rect rect = drawable.getBounds();
      int width = rect.right - rect.left;
      int height = rect.bottom - rect.top;
      int color = ((ColorDrawable)drawable).getColor();
      Bitmap bitmap = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
      Canvas canvas = new Canvas(bitmap);
      canvas.drawARGB(Color.alpha(color),Color.red(color), Color.green(color), Color.blue(color));
      return bitmap;
    }else {
      return null;
    }
  }


  /**
   *     
   * @param source
   * @return
   */
  private Bitmap createRoundConerImage(Bitmap source) {
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    Bitmap target = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(target);
    RectF rect = new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight());
    canvas.drawRoundRect(rect, mRadius, mRadius, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(source, 0, 0, paint);
    return target;
  }

  /**
   *     
   * @param source
   * @param min
   * @return
   */
  private Bitmap createCircleImage(Bitmap source, int min) {
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    Bitmap target = Bitmap.createBitmap(min, min, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(target);
    canvas.drawCircle(min/2,min/2,min/2,paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(source, 0, 0, paint);
    return target;
  }
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기